import os
import socket
import _thread
import time
from util.message import Message

# Settings
ip = '127.0.0.1'
port = 8000

# Receiver
def receiver(a, b):
    while True:
        try:
            recv = client.recv(1024)
            msg = Message(recv)
            recv = client.recv(int(msg.data))
            msg = Message(recv)
            if msg.type == 2:
                print('|Notice: %s'%msg.data)
            else:
                print('|%s: %s'%(msg.fr, msg.data))
        except ConnectionResetError as e:
            print('Server disconnected. Press ENTER to exit.')
            break

# Open Client
try:
    client = socket.socket()
    client.connect((ip, port))
except ConnectionRefusedError as e:
    print('Unable to connect Server. Client will close after 3 seconds.')
    time.sleep(3)
    quit(0)

# User Login
while True:
    try:
        reg_flag = True
        # Input
        while True:
            uid = input('Enter user name:').strip()
            if uid != '':
                break
        client.send(Message.login(uid, 'check').encode('utf-8'))
        recv = client.recv(1024)
        msg = Message(recv)
        if not msg.data:
            option = input('Haven\'t been registered, register now? (Y/N) ').upper()
            if option != 'Y':
                os.system('cls')
                continue
        else:
            reg_flag = False
        # Input
        while True:
            pwd = input('Enter password:').strip()
            if pwd != '':
                break
        if reg_flag:
            client.send(Message.register(uid, pwd).encode('utf-8'))
            recv = client.recv(1024)
            msg = Message(recv)
            if msg.data == True:
                break
            else:
                print('Register failed.')
                continue
        else:
            client.send(Message.login(uid, pwd).encode('utf-8'))
            recv = client.recv(1024)
            msg = Message(recv)
            if msg.data == True:
                break
            else:
                print('Login failed.')
                continue
    except ConnectionResetError as e:
        print('Server disconnected. Client will close after 3 seconds.')
        time.sleep(3)
        quit(0)

# Initial
os.system('cls')
print('Welcome to chat room, enter your message or \':q\' to quit.')
_thread.start_new_thread(receiver, (None, None))

# Send Message
while True:
    msg = input()
    if(msg == ':q'):
        _thread.exit()
        client.close()
        quit(0)
    j = Message.broadcast(uid, msg)
    if len(j) > 50000:
        print('Content is too long to send.')
        continue
    else:
        client.send(Message.len(len(j)).encode('utf-8'))
        client.send(j.encode('utf-8'))